package jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import bean.LinkInfo;
import main.MainFrame;

/**
 * 用于两库数据比对
 * */
public class DataCheck {
	List<List<Object>> dataList1 = new ArrayList<List<Object>>();
	List<List<Object>> dataList2 = new ArrayList<List<Object>>();
	
	MainFrame mf = null;
	
	LinkInfo li;
	
	public DataCheck(){
		
	}
	
	public DataCheck(LinkInfo li,MainFrame mf){
		this.li = li;
		this.mf = mf;
	}
	
	public void queryData() {
		Statement st1 = null;
		ResultSet rs1= null;
		
		Statement st2= null;
		ResultSet rs2= null;
		try {
			st1 = JDBCTools.getConnection(li.getUsername1(),li.getPassword1(),li.getDriver1(),li.getUrl1()).createStatement();
			rs1 = st1.executeQuery(li.getSql1());
			
			pickData(rs1,dataList1);
			
			st1.close();
			rs1.close();
			
			
			st2 = JDBCTools.getConnection(li.getUsername2(),li.getPassword2(),li.getDriver2(),li.getUrl2()).createStatement();
			rs2 = st2.executeQuery(li.getSql2());
			
			pickData(rs2,dataList2);
			
			rs2.close();
			st2.close();
			
		} catch (SQLException e ) {
			mf.showErrorLogs(e.getMessage(),e.getStackTrace());
		}catch(ClassNotFoundException e){
			mf.showErrorLogs(e.getMessage(),e.getStackTrace());
		}
	}
	
	
	/**捡出数据存到List*/
	public void pickData(ResultSet rs,List<List<Object>> list){
		list.clear();
		int columns = 0;
		try {
			while(rs.next()){
				columns = rs.getMetaData().getColumnCount();
				List<Object> row = new ArrayList<Object>();
				for(int i=1;i<=columns;i++){
					Object o = rs.getObject(i);
					row.add(o);
				}
				list.add(row);
			}
		} catch (SQLException e) {
			mf.showErrorLogs(e.getMessage(),e.getStackTrace());
		}
	}
	
	/**
	 * 数据比对
	 * */
	public void check() {
		 for(List<Object> list :dataList1){
			 if(!dataList2.contains(list)){
				 mf.refreshMessage(mf.message1, null, "行："+(dataList1.indexOf(list)+1)+" 内容："+Arrays.deepToString(list.toArray()));
			 }
		 }
		 
		 for(List<Object> list :dataList2){
			 if(!dataList1.contains(list)){
				 mf.refreshMessage(mf.message2, null, "行："+(dataList2.indexOf(list)+1)+" 内容："+Arrays.deepToString(list.toArray()));
			 }
		 }
	}
}
